package com.jxb.broker.store;

import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

public class CommitLog {

    private static String storeFile = "C:\\Users\\86177\\Documents\\learn\\rocketmq\\store\\commitlog\\commit.log";

    public static int flush(Integer position, byte[] bytes) {
        try (RandomAccessFile file = new RandomAccessFile(storeFile, "rw")) {
            FileChannel channel = file.getChannel();
            // 获取文件锁以确保文件在被写入时不被其他进程访问
            FileLock lock = channel.lock();
            try {
                // 将文件映射到内存中
                MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, 1024);
                // 写入数据到内存映射区
                buffer.position(position);
                buffer.put(bytes);
                // 强制将缓冲区的数据写入文件，并清空缓冲区
                buffer.force();
                return position + bytes.length;
            } finally {
                // 释放文件锁
                lock.release();
                // 关闭文件通道
                channel.close();
                file.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return position;
    }
}
